package org.example.carsystem.config;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import org.example.carsystem.domain.SysUser;
import org.example.carsystem.domain.vo.DeptVo;
import org.example.carsystem.mapper.UserMapper;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

@Slf4j
public class UsersDataListener implements ReadListener<SysUser>{

    /**
     * 单次缓存的数据量
     */
    public static final int BATCH_COUNT = 3;

    private UserMapper userMapper;

    private RedisTemplate redisTemplate;

    public UsersDataListener(UserMapper userMapper, RedisTemplate redisTemplate) {
        this.userMapper = userMapper;
        this.redisTemplate = redisTemplate;
    }
    /**
     *临时存储
     */
    private List<SysUser> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    @Override
    public void invoke(SysUser data, AnalysisContext context) {
        List<DeptVo> deptVoList = (List<DeptVo>) redisTemplate.opsForValue().get("dept");
        System.out.println(deptVoList);
        String[] split = data.getDeptName().split("/");
        DeptVo deptVo = deptVoList.stream().filter(ss -> ss.getDeptName().equals(split[0])).findFirst().get();
        DeptVo dept = deptVoList.stream().filter(ss -> ss.getDeptName().equals(split[1]) && ss.getParentId() == deptVo.getDeptId()).findFirst().get();
        data.setDeptId(dept.getDeptId());
        data.setCreateBy("admin");
        cachedDataList.add(data);
        log.info("将要录入数据库的的数据:{}",data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("解析完成");
        if (!cachedDataList.isEmpty()){
            log.info("最后一次存储");
            saveData();
        }
    }
    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        userMapper.userImport(cachedDataList);
        log.info("存储数据库成功！");
    }
}
